import { User } from '@/types/user';

const prefix = 'suzhou-';
const defaultExpiredTime = 7 * 24 * 60 * 60 * 1000; // a week

function makeTimestamp(expiredTime: number) {
  const now = Date.now();
  return {
    timestamp: now,
    expired: now + expiredTime
  };
}

function createStorage<T>(key: string, storage: Storage, expiredTime?: number) {
  const prefixed = prefix + key;

  function get() {
    const item = storage.getItem(prefixed);
    if (!item) {
      return null;
    }
    const { value, expired } = JSON.parse(item);
    if (expired && expired < Date.now()) {
      clear();
      return null;
    }
    return value as T;
  }

  function set(value: T, expired = expiredTime) {
    const item = {
      value,
      ...(expired && makeTimestamp(expired))
    };
    storage.setItem(prefixed, JSON.stringify(item));
  }

  function update(value: Partial<T>) {
    const item = get();
    const newItem = Object.assign({}, item, value);
    set(newItem);
  }

  function clear() {
    storage.removeItem(prefixed);
  }

  return {
    get,
    set,
    update,
    clear
  };
}

function createLocalStorage<T>(key: string, expiredTime: number = defaultExpiredTime) {
  return createStorage<T>(key, localStorage, expiredTime);
}

function createSessionStorage<T>(key: string) {
  return createStorage<T>(key, sessionStorage);
}

/**
 * LocalStorage管理
 *
 * 为数据增加过期时间、时间戳
 */
const Storage = {
  lng: createLocalStorage<string>('lng'),
  login: createLocalStorage<User | null>('login'),
  exchangeProduct: createLocalStorage<any>('product'),
  loginCheck: createLocalStorage<boolean>('loginCheck'),
  browser: createLocalStorage<string>('browser')
};

export default Storage;
